package baseFx.database;

import baseFx.common.utils.ExceptionUtils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Utils {
    public static List<Map<?,?>> resultSetToList(ResultSet rs) {
        try {
            List<Map<?,?>> rows = new ArrayList<>();
            List<String> columns = new ArrayList<>();
            ResultSetMetaData meta = rs.getMetaData();
            for (int i = 1; i <= meta.getColumnCount(); i++) {
                columns.add(meta.getColumnLabel(i));
            }
            while (rs.next()) {
                Map<String, Object> row = new HashMap<>(meta.getColumnCount());
                for (String name : columns) {
                    row.put(name, rs.getObject(name));
                }
                rows.add(row);
            }
            return rows;
        } catch (SQLException e) {
            throw ExceptionUtils.toRuntime(e);
        }
    }

    public static Map<?,?> resultSetToMap(ResultSet rs) {
        try {
            ResultSetMetaData meta = rs.getMetaData();
            Map<String, Object> row = new HashMap<>(meta.getColumnCount());
            for (int i = 1; i <= meta.getColumnCount(); i++) {
                row.put(meta.getColumnLabel(i), rs.getObject(meta.getColumnLabel(i)));
            }
            return row;
        } catch (SQLException e) {
            throw ExceptionUtils.toRuntime(e);
        }
    }
}
